<script lang="ts" setup>
import { ref, watch, onMounted } from 'vue'
import type { SearchClazzModel, ClazzModel, ClazzModelArray, SearchEmpModel } from '@/api/model/model'
import axios from 'axios'
import { queryclazzList, queryAllEmpApi, addClazz, getClazzById, updateClazz, deleteClazzByIds } from '@/api/clazz/index'
import type { UploadProps, FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
// 页面顶部的搜索
const searchForm = ref<SearchClazzModel>({
  name: '',
  begin: '',
  end: '',
  date: []
})
const clear = () => {
  searchForm.value = {
    name: '',
    date: [],
    begin: '',
    end: ''
  }
}
//侦听searchEmp的date属性
watch(() => searchForm.value.date, (newVal, oldVal) => {
  if (newVal.length > 0) {
    searchForm.value.begin = newVal[0]
    searchForm.value.end = newVal[1]
  } else {
    searchForm.value.begin = ''
    searchForm.value.end = ''
  }
})

onMounted(() => {
  query();
  queryAllEmp();
});
//========================================分页查询==========================================================
const query = async () => {
  const res = await queryclazzList(searchForm.value.name, searchForm.value.begin, searchForm.value.end, currentPage.value, pageSize.value);
  clazzTable.value = res.data.rows;
  total.value = res.data.total;
}

const clazzTable = ref<ClazzModelArray>();
const currentPage = ref(1)
const pageSize = ref(5);
const total = ref(0)
function handleSizeChange() {
  query()
}

function handleCurrentChange() {
  query()
}
//========================================新增班级============================================================
/* const add */
// 新增修改弹框的标题
const dialogTitle = ref('新增部门')
//是否展示弹窗
let dialogFormVisible = ref(false)
let form = ref<ClazzModel>({
  id: '',
  name: '',
  room: '',
  beginDate: '',
  endDate: '',
  status: '',
  subject: '',
  masterId: '',
  masterName: '',
  updateTime: ''
})
// 打开新增的弹框
function openAddDialog() {
  dialogFormVisible.value = true;
  dialogTitle.value = "新增班级"
}
let masterList = ref([
  {
    id: '',
    name: ''
  }
])
const queryAllEmp = async () => {
  let result = await queryAllEmpApi()
  console.log(result.data)
  masterList.value = result.data
  console.log(masterList.value)
}
//保存按钮
const doAddOrUpdate = (formEL: FormInstance | undefined) => {
  // console.log("insertOrUpdate");
  if (!formEL) {
    return;
  }
  // 先校验表单的格式
  formEL.validate(async (valid) => {
    if (valid) {
      // 校验通过
      let res = null;
      let insertFlag = null;
      if (form.value.id) {//修改
        insertFlag = false;
        res = await updateClazz(form.value);
      } else {// 新增
        insertFlag = true;
        res = await addClazz(form.value);
      }
      if (!res.code) {
        ElMessage.error(res.msg);
      } else {
        // 隐藏dialog
        dialogFormVisible.value = false;
        // 清空dialog，通过dialog的回调统一处理
        ElMessage({ type: 'success', message: insertFlag ? '添加成功' : '修改成功', })
        query();
      }
    }
  });
}
// 更新
const handleEdit = async (idx: number, row: ClazzModel) => {
  // 展示弹框
  dialogFormVisible.value = true;
  dialogTitle.value = "修改班级";
  // 回显查询，参数是id
  const res = await getClazzById(row.id!);
  form.value = res.data;
}
//表单校验
const rules = ref<FormRules<ClazzModel>>({
  name: [
    { required: true, message: '班级名称不能为空', trigger: 'blur' },
    { min: 4, max: 30, message: '班级名称长度在4-30个字之间', trigger: 'blur' },
  ],
  room: [
    { required: true, message: '班级教室不能为空', trigger: 'blur' }
  ],
  beginDate: [
    { required: true, message: '开课时间不能为空', trigger: 'blur' }
  ],
  endDate: [
    { required: true, message: '结课时间不能为空', trigger: 'blur' }
  ],
  subject: [
    { required: true, message: '学科不能为空', trigger: 'blur' }
  ]
})
const dialogFromRef = ref<FormInstance>();
//关闭时自动回调
function dialogClose() {
  form.value =
  {
    id: '',
    name: '',
    room: '',
    beginDate: '',
    endDate: '',
    status: '',
    subject: '',
    masterId: '',
    masterName: '',
    updateTime: ''
  }
  // 重置form校验规则
  // formRef.value.resetFields();
}

//删除
const handleDelete = (idx: number, row: ClazzModel) => {
  ElMessageBox.confirm(
    '您确认删除此数据吗?',
    '确认删除',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    // 发删除请求
    const res = await deleteClazzByIds('' + row.id);
    if (!res.code) {
      ElMessage({ type: 'error', message: res.msg, })
    } else {
      ElMessage({ type: 'success', message: '删除成功' })
      // 刷新页面
      query();
    }
  })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
</script>


<template>
  <span class="title">班级管理</span>

  <!----------------------------------搜索框-------------------------------------->
  <el-form :inline="true" :model="searchForm" class="demo-form-inline">
    <el-form-item label="班级名称">
      <el-input v-model="searchForm.name" placeholder="请输入班级名称" style="width:200px" clearable />
    </el-form-item>
    <el-form-item label="结课时间">
      <el-date-picker v-model="searchForm.date" value-format="YYYY-MM-DD" type="daterange" range-separator="至"
        start-placeholder="开始时间" end-placeholder="结束时间" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="query">查询</el-button>
      <el-button type="primary" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>
  <el-button type="primary" @click="openAddDialog">+ 新增班级</el-button>

  <!----------------------------------数据列表-------------------------------------->
  <el-table :data="clazzTable" border style="width: 100%; margin-top:10px">
    <el-table-column prop="id" label="序号" width="80" align="center" />
    <el-table-column prop="name" label="班级名称" width="180" align="center" />
    <el-table-column prop="room" label="班级教室" width="100" align="center" />
    <el-table-column prop="masterName" label="班主任" width="100" align="center" />
    <el-table-column prop="beginDate" label="开课时间" width="180" align="center" />
    <el-table-column prop="endDate" label="结课时间" width="180" align="center" />
    <el-table-column prop="status" label="状态" width="100" align="center" />
    <el-table-column prop="updateTime" label="最后修改时间" width="180" align="center" />
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>
        <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <!----------------------------------分页组件---------------------------------------->
  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30, 40]"
    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
    @current-change="handleCurrentChange" style="margin-top:10px" />
  <!----------------------------------新增班级弹窗---------------------------------------->
  <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="540px" @close="dialogClose">
    <el-form :model="form" ref="dialogFromRef" :rules="rules">
      <el-form-item label="班级名称" prop="name">
        <el-input v-model="form.name" autocomplete="off" style="width:100%" placeholder="请输入班级名称" />
      </el-form-item>
      <el-form-item label="班级教室" prop="room">
        <el-input v-model="form.room" autocomplete="off" style="width:100%" placeholder="请输入班级教室" />
      </el-form-item>
      <el-form-item label="开课时间" style="width:100%" prop="beginDate">
        <el-date-picker style="width:100%" v-model="form.beginDate" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择开课时间" />
      </el-form-item>
      <el-form-item label="结课时间" style="width:100%" prop="endDate">
        <el-date-picker style="width:100%" v-model="form.endDate" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择结课时间" />
      </el-form-item>
      <el-form-item label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;班主任" style="width:100%">
        <el-select v-model="form.masterId" placeholder="请选择" style="width:100%" clearable>
          <el-option v-for="master in masterList" :label="master.name" :value="master.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;学科" prop="subject">
        <el-select v-model="form.subject" placeholder="请选择" style="width: 100%">
          <el-option label="java" value="1" />
          <el-option label="前端" value="2" />
          <el-option label="大数据" value="3" />
          <el-option label="Python" value="4" />
          <el-option label="Go" value="5" />
          <el-option label="嵌入式" value="6" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="doAddOrUpdate(dialogFromRef)">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scope>
.title {
  font-size: 20px;
  font-weight: 600;
}

.demo-form-inline {
  margin-top: 10px
}
</style>